/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.all;

import dao.BinhluanDAO;
import dao.SanphamDAO;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import pojo.Binhluan;
import pojo.BinhluanId;
import pojo.Nguoidung;
import pojo.Sanpham;

/**
 *
 * @author BlueZky
 */
public class chiTietSanPhamController extends AbstractController {

    public chiTietSanPhamController() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("UTF-8");
        ModelAndView mv = null;
        HttpSession session = request.getSession();
        Nguoidung nguoiDung = (Nguoidung) session.getAttribute("nguoiDung");
        String PID = request.getParameter("PID");
        Sanpham sp = null;
        List<Sanpham> danhSach = null;
        
        if (PID == null || PID.length() == 0 || !PID.matches("^[0-9]*$")) {
            sp = SanphamDAO.layThongTin(101);
        } else {

            sp = SanphamDAO.layThongTin(Integer.parseInt(PID));
            if (nguoiDung != null) {
                String action = request.getParameter("a");
                boolean rs = false;
                Binhluan binhluan = null;
                if (action != null && action.compareTo("post") == 0) {
                    String comment = request.getParameter("comment");
                    if (comment != null && comment.length() > 20) {
                        binhluan = new Binhluan(new BinhluanId(sp.getMasp(), 1), sp, nguoiDung, comment, new Date(new java.util.Date().getTime()));
                        rs = BinhluanDAO.themBinhLuan(binhluan);
                    }
                }
                if (rs) {
                    sp.getBinhluans().add(binhluan);
                }
            }
        }

        danhSach = SanphamDAO.layDanhSach(5);

        mv = new ModelAndView("All/index");
        mv.addObject("tag", "chitiet");
        mv.addObject("sanPham", sp);
        mv.addObject("danhSach", danhSach);
        mv.addObject("binhluan", sp.getBinhluans());
        return mv;
    }
}
